package hhf.flex.soundapi.ui {
	import flash.display.CapsStyle;
	import flash.display.Graphics;
	import flash.display.GraphicsPathCommand;
	import flash.display.JointStyle;
	import flash.display.LineScaleMode;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.media.SoundMixer;
	import flash.utils.ByteArray;
	
	import hhf.flex.soundapi.core.SoundEvent;
	
	import mx.core.Application;
	import mx.core.UIComponent;

	[Style(name="cursorColor", type="uint", format="Color", inherit="yes")]
	[Event(name="cursorMove", type="hhf.flex.soundapi.core.SoundEvent")]

	public class Cursor  extends UIComponent {
		public function Cursor() {
			super();
			this.setStyle("cursorColor", 0x000000);
		}
		
		private var inDrag:Boolean = false;
		private function mouseDownHandler(event:MouseEvent):void {
			trace("mouseDown");
			addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
			addEventListener(MouseEvent.MOUSE_OUT, mouseUpHandler);
			addEventListener(MouseEvent.MOUSE_MOVE, mouseDragHandler);
		}
		
		private function mouseDragHandler(event:MouseEvent):void {
			var start:Number = (event.localX*(maximum-minimum))/this.width;
			trace("mouseDrag : "+start);
			dispatchEvent(new SoundEvent(SoundEvent.CURSORMOVE, start));
		}
		private function mouseUpHandler(event:MouseEvent):void {
			trace("endDrag");
			removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
			removeEventListener(MouseEvent.MOUSE_OUT, mouseUpHandler);
			removeEventListener(MouseEvent.MOUSE_MOVE, mouseDragHandler);
		}

		[Bindable]
		public var _value:Number = 0;
		public function set value(value:Number):void {
			if(value!=_value) {
				addEventListener(Event.ENTER_FRAME, drawCursorOnRender);
				drawCursor(value);
			}
			_value=value;
		}
		public function get value():Number {
			return _value;
		}
		[Bindable]
		public var minimum:Number = 0;
		[Bindable]
		public var maximum:Number = 100;

		/**
		 * Dessine pendant le render de la scene
		 */
		private function drawCursorOnRender(e:Event=null):void {
			drawCursor(value);
		}
		
		/**
		 * Dessine le cursor
		 */
		private function drawCursor(value:Number):void {
			var x:int = value*this.width/maximum-minimum
			var g:Graphics = this.graphics;
			g.clear();
			g.lineStyle(3, getStyle("cursorColor"), 0.5, false, LineScaleMode.NORMAL, CapsStyle.ROUND, JointStyle.ROUND);
			g.moveTo(x, 0);
			g.lineTo(x, this.height);
			removeEventListener(Event.ENTER_FRAME, drawCursorOnRender);
		}
	}
}